<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "config".
 *
 * @property string $id
 * @property string $key 键
 * @property string $value 值
 * @property string $explain 说明
 * @property string $update_time
 * @property string $create_time
 */
class ConfigModel extends \backend\base\BaseModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'config';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['key'], 'required' , 'on'=>['add','edit']],
            [['class','update_time', 'create_time'], 'integer'],
            [['key','explain'], 'string', 'max' => 255],
            [['value'], 'string', 'max' => 8000],
            [['key'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'class' => '类别',
            'key' => '键',
            'value' => '值',
            'explain' => '说明',
            'update_time' => '更新时间',
            'create_time' => '创建时间',
        ];
    }
    /**
     * 保存前
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        $time = time();
        if(parent::beforeSave($insert)){
            if($this->isNewRecord){
                $this->create_time = $time;
                $this->status = 1;
            }else{
                //修改key,销毁旧key
                if($this->key != $this->getOldAttribute('key')){
                    self::cacheSet($this->getOldAttribute('key'),null);
                }
            }
            $this->update_time = $time;
            return true;
        }
        return false;
    }

    private static function cacheGet($key){
        return Yii::$app->redis->get('config_'.$key);
    }

    public static function cacheSet($key,$data){
        return Yii::$app->redis->set('config_'.$key,$data);
    }

    public static function cacheDel($key){
        return Yii::$app->redis->del('config_'.$key);
    }

    public static function get($key){
        if(($data = static::cacheGet($key))){
            return $data;
        }
        $mdl = self::findOne($key);
        if($mdl){
            static::cacheSet($key,$mdl->value);
            return $mdl->value;
        }else{
            return '';
        }
    }

}
